#include<iostream>
#include <unistd.h>
#include<sys/socket.h>
#include <netinet/in.h>
#include<arpa/inet.h>
#include <string.h>
using namespace std;

class tcpClient
{
private:
    int _sock;
    int service_port;
    string service_ip;
public:
    tcpClient(string ip,int port)
        :_sock(-1),
        service_ip(ip),
         service_port(port)
    {}
    ~tcpClient()
    {
        if(_sock>0)
        {
            close(_sock);
        }
    }
    void InitClient()
    {
        _sock=socket(AF_INET,SOCK_STREAM,0);
        if(_sock<0)
        {
            cout<<"sock creat error"<<endl;
            exit(2);
        }
        cout<<"sock creat success"<<endl;
    }
    void Resquet()
    {
        string msg;
        char buffer[128];
        while(true)
        {
            cout<<"plese Enter#";
            getline(cin,msg);
            write(_sock,msg.c_str(),msg.size());
            ssize_t size=read(_sock,buffer,sizeof(buffer)-1);
            if(size>0)
            {
                buffer[size]='\0';
                cout<<"server echo#"<<buffer<<endl;
            }else if(size==0)
            {
                cout<<"server close"<<endl;
                break;
            }else
            {
                cout<<"read error"<<endl;
                break;
            }
        }
    }
    void Start()
    {
        struct sockaddr_in peer;
        memset(&peer,'\0',sizeof(peer));
        peer.sin_family=AF_INET;
        peer.sin_port=htons(service_port);
        peer.sin_addr.s_addr=inet_addr(service_ip.c_str());

        int f_connect=connect(_sock,(struct sockaddr*)&peer,sizeof(sockaddr));
        if(f_connect<0)
        {
            cout<<"connect service["<<service_ip<<"]error"<<endl;
            exit(3);
        }else
        {
            cout<<"connect success"<<endl;
            Resquet();
        }
    }
};

void Usage(string proc)
{
    cout<<"Usage:"<<proc<<"server_ip serverport"<<endl;
}

int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string server_ip=argv[1];
    int server_port=atoi(argv[2]);
    tcpClient*clt=new tcpClient(server_ip,server_port);
    clt->InitClient();
    clt->Start();
}
